package cz.zcu.fav.rat.dataaccess.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cz.zcu.fav.rat.beans.Object;
import cz.zcu.fav.rat.beans.Reservation;
import cz.zcu.fav.rat.beans.User;
import cz.zcu.fav.rat.dataaccess.dao.PeriodDAO;
import cz.zcu.fav.rat.dataaccess.dao.ReservationDAO;
import cz.zcu.fav.rat.dataaccess.dao.UserDAO;
import cz.zcu.fav.rat.dataaccess.service.ReservationService;
import cz.zcu.fav.rat.dataaccess.service.UserService;

@Service("userService")
@Transactional
public class UserServiceImpl extends GenericDataServiceImpl<User, UserDAO>
		implements UserService
{
	@Autowired
	ReservationService reservationService;

	@Autowired
	public UserServiceImpl(UserDAO dao)
	{
		super(dao);
	}

	@Override
	@Transactional(readOnly = false)
	@Secured("ROLE_ADMIN")
	public void delete(User persistentObject)
	{
		List<Reservation> reservations = reservationService
				.getAllReservationsByUserId(persistentObject.getId());
		reservationService.deleteCollection(reservations);
		persistentObject = merge(persistentObject);
		super.delete(persistentObject);
	}

	@Override
	@Transactional(readOnly = true)
	public List<User> findBySurname(String name)
	{
		return dao.findBySurname(name);
	}

	@Override
	public List<User> findByNickname(String nickname)
	{
		return dao.findByNickname(nickname);
	}

	@Override
	public List<User> findByNicknameAndImplementor(String nickname,
			String implementor)
	{
		return dao.findByNicknameAndImplementor(nickname, implementor);
	}

	@Override
	public void saveOrUpdate(User persistentObject)
	{
		dao.saveOrUpdate(persistentObject);
	}

	@Override
	@Transactional(readOnly = false)
	public void addNewFavouriteToUser(User user, Object object)
	{
		if (!user.getFavourites().contains(object))
		{
			// TODO: logger!
			user.addFavourite(object);
			update(user);
		}
	}

	@Override
	@Transactional(readOnly = false)
	public void removeFavouriteToUser(User user, Object object)
	{
		if (user.getFavourites().contains(object))
		{
			user.removeFavourite(object);
			update(user);
		}
		// TODO: logger!
	}

	@Override
	@Transactional(readOnly = true)
	public boolean isObjectUsersFavourite(Integer userId, Integer objectId)
	{
		List<User> users = dao.findIfUserHasFavouriteId(userId, objectId);
		return !users.isEmpty();
	}
}
